﻿@model int
@inject IPictureService pictureService

@using Urs.Core;
@using Urs.Services.Media

@{
    const int pictureSize = 100;
    //other variables
    var random = CommonHelper.GenerateRandomInteger();
    var clientId = "picture" + random;
    var pictureUrl = pictureService.GetPictureUrl(Model,targetSize: pictureSize);
}
<div class="layui-upload">
    <button type="button" class="layui-btn" id="@clientId">上传图片</button>
    <div class="layui-upload-list" id="@(clientId + "value")">
        <img class="layui-upload-img" id="@(clientId)-picture" src="@pictureUrl">
        <input type="hidden" asp-for="@Model" />
        <p id="@(clientId)-msg"></p>
    </div>
</div>
<script>
    layui.use('upload', function () {
        var $ = layui.jquery
            , upload = layui.upload;
        //普通图片上传
        var uploadInst = upload.render({
            elem: '#@clientId'
            , url: '@(Url.Content("~/Admin/Picture/AsyncUpload"))'
            , before: function (obj) {
                //预读本地文件示例，不支持ie8
                obj.preview(function (index, file, result) {
                    $('#@(clientId)-picture').attr('src', '/icon/loading-lizi.gif'); //图片链接（base64）
                });
            }
            , done: function (res) {
                //如果上传失败
                if (res.error > 0) {
                    return layer.msg('上传失败');
                }
                if (res.success) {
                    $("#@(clientId + "-picture")").attr('src', res.imageUrl);
                    $("#@(clientId + "value") input").val(res.pictureId);
                }
                //上传成功
            }
            , error: function () {
                //演示失败状态，并实现重传
                var demoText = $('#@(clientId)-msg');
                demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                demoText.find('.demo-reload').on('click', function () {
                    uploadInst.upload();
                });
            }
        });
    });
</script>
